package com.baobaotao.dao;

import com.baobaotao.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by xu on 2016/3/18.
 */
@Repository //1.通过Spring注解定义一个DAO
public class UserDao {

    @Autowired  //2.自动注入JdbcTemplate的Bean
    private JdbcTemplate jdbcTemplate;

    public int getMatchCount(String userName,String password){
        String sqlStr = "select count(*) from t_user where user_name = ? and password = ?";
        return  jdbcTemplate.queryForInt(sqlStr,new Object[]{userName,password});
    }

//    public int getMatchCount(String userName,String password){
//        String sqlStr = "select count(*) from t_user where user_name = :userName and password = :password";
//        NamedParameterJdbcTemplate parameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
//
//        return  parameterJdbcTemplate.queryForInt(
//                sqlStr,
//                new BeanPropertySqlParameterSource(new User(userName, password))
//        );
//    }

    public User findUserByUserName(final String userName){
        //1.根据用户名查询用户的sql语句
        String sqlStr = "select user_id,user_name,credits from t_user Where user_name = ?";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{userName},
                //2.匿名类方式实现的回调函数
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserName(userName);
                        user.setCredits(rs.getInt("credits"));
                    }
                });
        return user;
    }

    public void updateLoginInfo(User user){
        String sqlStr = "update t_user set last_visit=?,last_ip=?,credits=? where user_id=?";
        jdbcTemplate.update(sqlStr,new Object[]{user.getLastVisit(),user.getLastIp(),user.getCredits(),user.getUserId()});
    }
}
